package com.linewell.commom.controller;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.linewell.commom.model.SecondMarket;
import com.linewell.commom.service.ISecondMarketService;
import com.linewell.system.pagemodel.DataGrid;
import com.linewell.system.pagemodel.PageHelper;
import com.linewell.system.pagemodel.ReturnInfo;
import com.linewell.system.utils.ConfigProperty;
import com.linewell.system.utils.FileUploadUtil;

/**
 * 二手市场信息控制器类
 */
@Controller
@RequestMapping("/manage/secondMarket")
public class SecondMarketController extends BackendBaseController{
	private static final Log log = LogFactory.getLog(SecondMarket.class);

	@Autowired
	private ISecondMarketService secondMarketService;

	/**
	 *跳转到second_market_list页面
	 */
	@RequestMapping(value = "/index")
	public String index(HttpServletRequest request) {

		return super.index("/WEB-INF/pages/common/second_market/second_market_list.jsp", request);
	}

	/**
	 * 数据查询
	 */
	@ResponseBody
	@RequestMapping(value = "/dataGrid")
	public DataGrid dataGrid(@ModelAttribute SecondMarket s,PageHelper ph,HttpServletRequest request) {
		ph.setSort("marketId");
		ph.setOrder("desc");
		DataGrid dg = secondMarketService.datagrid(ph,s,getUserDepId(request));
		return dg;
	}
	
	/**
	 * 添加
	 */
	@RequestMapping(value = "/add")
	public String add(Map<String, Object> map) {
		map.put("saveUrl", "/manage/secondMarket/addSave");
		return "/WEB-INF/pages/common/second_market/second_market_au.jsp";
	}
	
	/**
	 * 添加保存
	 */
	@ResponseBody
	@RequestMapping(value = "/addSave")
	public ReturnInfo addSave(@Valid SecondMarket secondMarket, BindingResult b, ReturnInfo result, @RequestParam(value = "uploadFile", required = false) MultipartFile file, HttpServletRequest request) {
		if (b.getErrorCount() > 0) { // 数据校验
			for (FieldError error : b.getFieldErrors()) {
				log.info(error.getField() + ":" + error.getDefaultMessage());
				result.setMsg(error.getDefaultMessage());
			}
			result.setSuccess(1);
		} else {
			if (secondMarket != null) {
				if(file != null){
					try {
						String icon_url = FileUploadUtil.saveFile(file, request, ConfigProperty.getProperty("fileUplaodPath", "config") + "photo");
						secondMarket.setPhoto(icon_url);
					} catch (Exception e) {
						log.info("上传异常"+e.getMessage());
					}
				}
				try {
					secondMarketService.save(secondMarket);
				} catch (Exception e) {
					log.info("保存失败" + e.getMessage());
					result.setMsg("保存失败！");
					result.setSuccess(1);
				}
			}
		}
		return result;
	}

	/**
	 * 修改
	 */
	@RequestMapping(value = "/edit")
	public String edit(String id, Map<String, Object> map) {
		map.put("saveUrl", "/manage/secondMarket/editSave");
		if (id != null) {
			List<SecondMarket> model = secondMarketService.getUser(id);
			map.put("model", model.get(0));
		}
		return "/WEB-INF/pages/common/second_market/second_market_au.jsp";
	}

	/**
	 * 修改保存
	 */
	@ResponseBody
	@RequestMapping(value = "/editSave")
	public ReturnInfo editSave(@Valid SecondMarket secondMarket, BindingResult b, ReturnInfo result, @RequestParam(value = "uploadFile", required = false) MultipartFile file, HttpServletRequest request) {
		if (b.getErrorCount() > 0) { // 数据校验
			log.info("数据校验出错！");
			for (FieldError error : b.getFieldErrors()) {
				log.info(error.getField() + ":" + error.getDefaultMessage());
				result.setMsg(error.getField() + "" + error.getDefaultMessage());
			}
			result.setSuccess(1);
		} else {
			if (secondMarket != null) {
				if(file != null){
					try {
						String icon_url = FileUploadUtil.saveFile(file, request, getConfigAttr("fileUplaodPath") + "photo");
						secondMarket.setPhoto(icon_url);
					} catch (Exception e) {
						log.info("上传异常"+e.getMessage());
					}
				}
				try {
					secondMarketService.update(secondMarket);
				} catch (Exception e) {
					log.info("修改异常" + e.getMessage());
					result.setMsg("修改失败");
					if(secondMarket.getSysDepartment().getDepId() == null){
						result.setMsg("请选择部门！");
					}
					result.setSuccess(1);
				}

			}
		}

		return result;
	}
	
	/**
	 * 删除（物理删除）
	 */
	@ResponseBody
	@RequestMapping(value = "/delete")
	public ReturnInfo delete(String ids, ReturnInfo result) {
		if (ids != null) {
			try {
				secondMarketService.deleteAll(ids);
			} catch (Exception e) {
				log.info("删除异常" + e.getMessage());
				result.setMsg("删除失败！");
				result.setSuccess(1);
			}
		}

		return result;
	}

	/**
	 * 移除(逻辑删除)
	 */
	@ResponseBody
	@RequestMapping(value = "/remove")
	public ReturnInfo remove(String ids, ReturnInfo result) {

		if (ids != null) {
			try {
				secondMarketService.removeAll(ids);
			} catch (Exception e) {
				log.info("移除异常" + e.getMessage());
				result.setMsg("移除失败！");
				result.setSuccess(1);
			}
		}

		return result;
	}
	
	public String getConfigAttr(String str) {
		String attrStr = null;
		Properties prop = new Properties();
		InputStream is = this.getClass().getResourceAsStream("/config.properties");
		try {
			prop.load(is);
			attrStr = prop.getProperty(str);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return attrStr;
	}
}
